package com.jus.player.activity.home;

import static com.jus.player.api.OkHttpHelper._DATA;
import static com.jus.player.util.CommonUtils.showToast;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Debug;
import android.os.SystemClock;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson2.JSONObject;
import com.bumptech.glide.Glide;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.DefaultRenderersFactory;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.extractor.mp4.Mp4Extractor;
import com.google.android.exoplayer2.mediacodec.MediaCodecInfo;
import com.google.android.exoplayer2.mediacodec.MediaCodecSelector;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil;
import com.google.android.exoplayer2.source.BundledExtractorsAdapter;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.jus.player.R;
import com.jus.player.activity.BaseActivity;
import com.jus.player.adapter.JsPlayerAdaptor;
import com.jus.player.adapter.home.EpisodeAdapter;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.config.AppConfig;
import com.jus.player.dao.AppDatabase;
import com.jus.player.dao.WatchHistoryDao;
import com.jus.player.entity.VideoEntity;
import com.jus.player.entity.WatchHistory;
import com.jus.player.fragment.UnlockDialogFragment;
import com.jus.player.util.CommonUtils;
import com.jus.player.util.StringUtils;
import com.jus.player.util.Utils;
import com.jus.player.util.cache.PreloadManager;
import com.jus.player.util.cache.ProxyVideoCacheManager;
import com.jus.player.widget.VerticalViewPager;
import com.jus.player.widget.render.PlayerRenderViewFactory;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import xyz.doikki.videocontroller.StandardVideoController;
import xyz.doikki.videoplayer.exo.ExoMediaPlayerFactory;
import xyz.doikki.videoplayer.player.BaseVideoView;
import xyz.doikki.videoplayer.player.VideoView;
import xyz.doikki.videoplayer.util.L;

public class JsPlayerActivity extends BaseActivity<VideoView> implements
        JsPlayerAdaptor.OnItemBtnClickListener, EpisodeAdapter.OnItemEpisodeClickListener,
        UnlockDialogFragment.OnDialogCloseListener {

    private final List<VideoEntity> mVideoList = new ArrayList<>();
    /**
     * 当前播放位置
     */
    public VideoView vv;
    private int mCurPos;
    private long progress;
    private JsPlayerAdaptor adapter;
    private VerticalViewPager mViewPager;
    private PreloadManager mPreloadManager;
    //private PlayerController mController;
    private StandardVideoController mController;
    private BottomSheetDialog dialog;

    private WatchHistoryDao mHistoryDao;

    private static int mIndex;
    private static Long mTvId;
    private static boolean mShowDialog;
    private static long userId;
    private static boolean firstStart;

    public static void start(Context context, int index, Long tvId, boolean showDialog) {
        mIndex = index;
        mTvId = tvId;
        mShowDialog = showDialog;
        firstStart = true;
        context.startActivity(new Intent(context, JsPlayerActivity.class));
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_js_player;
    }

    @Override
    protected void initView() {
        // 初始化数据库
        mHistoryDao = AppDatabase.getInstance(this).watchHistoryDao();
        setStatusBarTransparent();
        initViewPager();
        initVideoView();
        mPreloadManager = PreloadManager.getInstance(this);
    }

    @Override
    protected void initData() {
        String userIdStr = CommonUtils.findFromSp(this, AppConfig.SP_USER_ID);
        userId = StringUtils.isEmpty(userIdStr) ? 0 : Long.parseLong(userIdStr);
        //初始化数据
        loadHistoryAndPlay();
    }

    @Override
    protected void onPause() {
        super.onPause();
        synchronized (AppConfig.historyLock) {
            saveCurrentProgress(false);
        }
        if (mVideoView != null) {
            mVideoView.pause();
        }
    }

    @Override
    protected void onDestroy() {
        // 1. 停止所有预加载
        mPreloadManager.removeAllPreloadTask();
        // 2. 释放所有ViewPager中的播放器
        if (adapter != null) {
            for (int i = 0; i < adapter.getCount(); i++) {
                View view = adapter.getViewByPosition(i);
                if (view != null) {
                    JsPlayerAdaptor.ViewHolder holder = (JsPlayerAdaptor.ViewHolder) view.getTag();
                    if (holder != null) holder.releasePlayer();
                }
            }
        }
        // 3. 释放主播放器
        if (mVideoView != null) {
            mVideoView.release();
            mVideoView = null;
        }
        // 4. 清除缓存（保留磁盘缓存，仅清除内存缓存）
        ProxyVideoCacheManager.clearAllCache(this);
        Glide.get(this).clearMemory();
        super.onDestroy();
    }

    /**
     * 初始化视频播放页面
     */
    private void initViewPager() {
        //设置预加载页面数量
        mViewPager = findViewById(R.id.player_vv_pager);
        mViewPager.setOffscreenPageLimit(2);
        adapter = new JsPlayerAdaptor(this, this);
        adapter.setVideoList(mVideoList);
        mViewPager.setAdapter(adapter);
        mViewPager.setOverScrollMode(View.OVER_SCROLL_NEVER);
        //注册监听器，监听页面变化事件：滑动，选中...
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            private int mCurItem;
            /**
             * VerticalViewPager是否反向滑动
             */
            private boolean mIsReverseScroll;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                if (position == mCurItem) {
                    return;
                }
                mIsReverseScroll = position < mCurItem;
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                // 仅预加载相邻1个视频
                mPreloadManager.removeAllPreloadTask();
                if (position < mVideoList.size() - 1) {
                    mPreloadManager.addPreloadTask(mVideoList.get(position + 1).getTvDownloadUrl(), position + 1);
                }
                if (position == mCurPos) return;
                synchronized (AppConfig.historyLock) {
                    saveCurrentProgress(false);
                }
                if (!firstStart) {
                    startPlay(position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
                if (state == VerticalViewPager.SCROLL_STATE_DRAGGING) {
                    mCurItem = mViewPager.getCurrentItem();
                }
                if (state == VerticalViewPager.SCROLL_STATE_IDLE) {
                    mPreloadManager.resumePreload(mCurPos, mIsReverseScroll);
                } else {
                    mPreloadManager.pausePreload(mCurPos, mIsReverseScroll);
                }
            }
        });
    }

    private void loadHistoryAndPlay() {
        // 先显示加载界面
        CommonUtils.showLoading(this);
        new Thread(() -> {
            // 查询历史记录
            WatchHistory history = mHistoryDao.getByVideoIdAndUserId(mTvId, userId);
            runOnUiThread(() -> {
                if (history != null) {
                    mIndex = history.getEpisode() - 1;
                    progress = history.getProgress();
                } else {
                    progress = -1;
                }
                requestData(mTvId);
            });
        }).start();
    }

    private void saveCurrentProgress(boolean complete) {
        if (mVideoView == null || (!complete && mVideoView.getDuration() <= 0)) {
            return;
        }
        long progress = mVideoView.getCurrentPosition();
        long duration = mVideoView.getDuration();
        if (progress >= (complete ? 0 : 10000)) {
            Integer episode = mVideoList.get(mCurPos).getEpisode();
            new Thread(() -> {
                WatchHistory history = new WatchHistory(
                        userId, mTvId,
                        mVideoList.get(0).getTitle(),
                        mVideoList.get(0).getTvCoverUrl(),
                        mVideoList.get(mCurPos).getTvDownloadUrl(),
                        progress, duration, System.currentTimeMillis(),
                        complete ? episode + 1 : episode,
                        mVideoList.get(mCurPos).getTotalEpisode()
                );

                List<WatchHistory> allByUserId = mHistoryDao.getAllByUserId(userId);
                if (allByUserId.size() > AppConfig.INT_200) {
                    mHistoryDao.delete(allByUserId.get(allByUserId.size() - 1));
                }
                WatchHistory his = mHistoryDao.getByVideoIdAndUserId(mTvId, userId);
                if (his != null) {
                    history.setId(his.getId());
                }
                mHistoryDao.insertOrUpdate(history);
            }).start();
        }

    }


    /**
     * 初始化视频页面
     */
    private void initVideoView() {
        mVideoView = new VideoView(this);
        vv = mVideoView;
        mVideoView.setLooping(false);
        //以下只能二选一，看你的需求
        mVideoView.setRenderViewFactory(PlayerRenderViewFactory.create());
        //mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_CENTER_CROP);
        mController = new StandardVideoController(this);
        //mController.addDefaultControlComponent("进度条", false);
        mVideoView.setVideoController(mController);
        mVideoView.setPlayerFactory(new ExoMediaPlayerFactory());
        //判断视频状态，播放结束自动播放下一个
        mVideoView.setOnStateChangeListener(new BaseVideoView.OnStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {
            }

            @Override
            public void onPlayStateChanged(int playState) {
                if (playState == BaseVideoView.STATE_PLAYBACK_COMPLETED) {
                    if (mCurPos + 1 > mVideoList.size() - 1) {
                        showToast(JsPlayerActivity.this, "已经是最后一条");
                    } else {
                        synchronized (AppConfig.historyLock) {
                            saveCurrentProgress(true);
                        }
                        mViewPager.setCurrentItem(mCurPos + 1, true);
                    }
                }
            }
        });
    }

    /**
     * 视频播放主方法
     *
     * @param position
     */
    private void startPlay(int position) {
        firstStart = false;
        // 安全校验
        if (position < 0 || position >= mVideoList.size() || isFinishing()) {
            return;
        }
        // 通过适配器获取视图
        View itemView = adapter.getViewByPosition(position);
        // 增加重试机制 缩短延迟时间但增加重试
        if (itemView == null) {
            mViewPager.postDelayed(() -> startPlay(position), 50);
            return;
        }
        JsPlayerAdaptor.ViewHolder viewHolder = (JsPlayerAdaptor.ViewHolder) itemView.getTag();
        // 3. 关键空指针检查
        if (viewHolder.mPlayerView == null || viewHolder.mPlayerContainer == null) {
            Log.e("播放错误", "PlayerView未正确初始化! position=" + position);
            return;
        }
        if (viewHolder.mPosition != position) {
            mViewPager.post(() -> startPlay(position));
            return;
        }
        // 播放逻辑
        mVideoView.release();
        Utils.removeViewFormParent(mVideoView);
        VideoEntity videoEntity = mVideoList.get(position);

        // 判断是否解锁
        if (!videoEntity.getUnlockState()) {
            UnlockDialogFragment dialog = UnlockDialogFragment.newInstance(mVideoList,
                    position, mViewPager, this);
            dialog.setOnDialogCloseListener(this);
            dialog.show(getSupportFragmentManager(), "UnlockDialogFragment");
            return;
        }

        String playUrl = mPreloadManager.getPlayUrl(videoEntity.getTvDownloadUrl());
        L.i("startPlay: " + "position: " + position + "  url: " + playUrl);
        mVideoView.setUrl(playUrl);
        mController.addControlComponent(viewHolder.mPlayerView, true);
        viewHolder.mPlayerContainer.addView(mVideoView, 0);
        mVideoView.start();
        mCurPos = position;

        if (progress >= 0) {
            mVideoView.seekTo(progress);
            progress = -1;
            showToast(this, getString(R.string.jumped_last_position));
        }
    }

    /**
     * 请求网络数据：查询选择短剧的剧集列表
     * * @param tvId 剧集ID
     */
    private void requestData(long tvId) {
        Map<String, String> map = new HashMap<>();
        map.put("tvId", tvId + "");
        OkHttpHelper.getInstance(this).getAsync(ApiConfig.EPISODE_TV_LIST, map,
                new OkHttpHelper.HttpCallback() {
                    @Override
                    public void onSuccess(String response) {
                        runOnUiThread(() -> {
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                            CommonUtils.hideLoading(JsPlayerActivity.this);
                            try {
                                JSONObject jo = JSONObject.parseObject(response);
                                JSONObject pageJo = jo.getJSONObject(_DATA);
                                List<VideoEntity> resList = pageJo.getList(OkHttpHelper._RECORD, VideoEntity.class);
                                // 使用新列表避免并发问题
                                List<VideoEntity> newList = new ArrayList<>(resList);
                                // 更新数据前暂停播放
                                if (mVideoView != null) {
                                    mVideoView.pause();
                                }
                                // 更新数据
                                mVideoList.clear();
                                mVideoList.addAll(newList);
                                adapter.setVideoList(newList);
                                // 显示对话框（如果需要）
                                if (mShowDialog) {
                                    showBottomSheetDialog(mVideoList);
                                }

                                // 设置新的页面位置
                                int targetPos = Math.min(mIndex, newList.size() - 1);
                                targetPos = Math.max(0, targetPos);

                                // 先确保ViewPager位置正确
                                mViewPager.setCurrentItem(targetPos, false);

                                // 延迟确保视图已更新
                                int finalTargetPos = targetPos;
                                mViewPager.postDelayed(() -> {
                                    if (!isFinishing() && !isDestroyed()) {
                                        startPlay(finalTargetPos);
                                    }
                                }, 200);
                            } catch (Exception e) {
                                showToast(JsPlayerActivity.this, "数据解析失败");
                            }
                        });
                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        runOnUiThread(() -> {
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                            CommonUtils.hideLoading(JsPlayerActivity.this);
                            CommonUtils.showToastAsync(JsPlayerActivity.this, e.getMessage());
                        });
                    }
                });
    }

    @Override
    public void onShowEpisodesClick(List<VideoEntity> videoList) {
        showBottomSheetDialog(videoList);
    }

    /**
     * 展开选集底部弹窗
     *
     * @param videoLis
     */
    private void showBottomSheetDialog(List<VideoEntity> videoLis) {

        VideoEntity video = videoLis.get(0);
        // 创建弹窗视图
        View dialogView = getLayoutInflater().inflate(R.layout.layout_dialog_episode, null);
        RecyclerView recyclerView = dialogView.findViewById(R.id.episode_recycler_view);
        TextView totalEpisode = dialogView.findViewById(R.id.total_episode);
        Button unlockButton = dialogView.findViewById(R.id.unlockButton);
        //立即解锁按钮 跳转解锁页面
        unlockButton.setOnClickListener(v -> {
            dialog.dismiss();
            UnlockDialogFragment dialog = UnlockDialogFragment.newInstance(mVideoList,
                    0, mViewPager, this);
            dialog.setOnDialogCloseListener(this);
            dialog.show(getSupportFragmentManager(), "UnlockDialogFragment");
        });
        //设置全剧总集数
        String string = getString(R.string.total_episodes, video.getTotalEpisode());
        SpannableString spannable = new SpannableString(string);
        String numberStr = String.valueOf(video.getTotalEpisode());
        int start = string.indexOf(numberStr);
        //spannable.setSpan(new ForegroundColorSpan(Color.RED),
        spannable.setSpan(new StyleSpan(Typeface.BOLD),
                start, start + numberStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        totalEpisode.setText(spannable);

        int count = 0;
        for (VideoEntity v : videoLis) {
            if (!v.getUnlockState()) {
                count++;
            }
        }
        //设置全局解锁折扣
        if (video.getDiscount() != null && video.getDiscount() > 0 && count > 0) {
            RelativeLayout unlockLayout = dialogView.findViewById(R.id.unlock_layout);
            unlockLayout.setVisibility(View.VISIBLE);
            TextView discountNumber = dialogView.findViewById(R.id.discountNumber);
            String fullText = getString(R.string.total_unlock_discount, String.valueOf(video.getDiscount()));
            SpannableString discountSpannable = new SpannableString(fullText);
            String discountStr = String.valueOf(video.getDiscount());
            int start1 = fullText.indexOf(discountStr);
            int end1 = start1 + discountStr.length();
            // 2. 红色（#FF0000）
            discountSpannable.setSpan(
                    new ForegroundColorSpan(Color.parseColor("#FF0000")),
                    start1, end1,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            );
            discountNumber.setText(discountSpannable);
        }
        // 这里使用GridLayoutManager来展示矩阵布局,注意：这里的6表示每行展示6个剧集
        recyclerView.setLayoutManager(new GridLayoutManager(this, 6));
        // 创建数据集和适配器
        EpisodeAdapter adapter = new EpisodeAdapter(getEpisodes(videoLis), this);
        recyclerView.setAdapter(adapter);
        // 设置RecyclerView的ItemDecoration来添加剧集间的间隔
       /*recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(3, 3, 3, 3); // 设置四周间距为3dp
            }
        });*/
        //----------------
        dialog = new BottomSheetDialog(this, R.style.TransparentBottomSheetDialog);
        dialog.setContentView(dialogView);
        // 将BottomSheetDialog的高度设置为屏幕高度的一半
       /* DisplayMetrics displayMetrics = new DisplayMetrics();
        requireActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int screenHeight = displayMetrics.heightPixels;*/
        ViewGroup.LayoutParams layoutParams = dialogView.getLayoutParams();
        layoutParams.height = (int) (getResources().getDisplayMetrics().heightPixels * 0.5f);
        dialogView.setLayoutParams(layoutParams);
        // 点击空白区域关闭弹窗
        dialogView.findViewById(R.id.close_dialog).setOnClickListener(v -> dialog.dismiss());
        if (!isFinishing() && !isDestroyed()) {
            dialog.show();
        }

    }

    // 获取全部剧集展示在弹窗
    private List<Map<String, Object>> getEpisodes(List<VideoEntity> videoLis) {
        // ... 获取剧集数据的逻辑 ...
        List<Map<String, Object>> episodes = new ArrayList<>();
        for (VideoEntity v : videoLis) {
            Map<String, Object> map = new HashMap<>();
            map.put("episode", v.getEpisode());
            map.put("unlock", v.getUnlockState());
            episodes.add(map);
        }
        return episodes;
    }

    @Override
    public void playSelectEpisode(int position, boolean unlock) {
        if (!unlock) {
            UnlockDialogFragment dialog = UnlockDialogFragment.newInstance(mVideoList,
                    position, mViewPager, this);
            dialog.setOnDialogCloseListener(this);
            dialog.show(getSupportFragmentManager(), "UnlockDialogFragment");
        } else {
            mViewPager.setCurrentItem(position, false);
        }
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public void onDialogClosedByBack() {
        finish();
    }

    @Override
    public void onDialogClosedFlushData(int position) {
        mIndex = position;
        mShowDialog = false;
        mVideoList.clear();
        CommonUtils.showLoading(this);
        requestData(mTvId);
    }

}